package tree;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class List2TreeMain {
    public static void main(String[] args) {
        ArrayList<Tree> allList = new ArrayList<>();
        Tree A = new Tree(1, "A", null, new ArrayList<>());
        Tree A1 = new Tree(2, "A1", 1, new ArrayList<>());
        Tree A11 = new Tree(3, "A12", 2, new ArrayList<>());
        Tree A2 = new Tree(4, "A2", 1, new ArrayList<>());
        Tree A21 = new Tree(5, "A21", 4, new ArrayList<>());
        Tree NP = new Tree(6, "NP", 100, new ArrayList<>());
        System.out.println("---树结构数据---");
        allList.add(A);
        allList.add(A1);
        allList.add(A11);
        allList.add(A2);
        allList.add(A21);
        allList.add(NP);

        // 结合数据转树结构
        List<Tree> trees = list2tree(allList);

        System.out.println(trees);


    }

    public static List<Tree> list2tree(List<Tree> allList) {
        // map
        HashMap<Integer, Tree> list2map = new HashMap<>();
        for (Tree tree : allList) {
            list2map.put(tree.getId(), tree);
        }
        List<Tree> root = new ArrayList<>();
        for (Map.Entry<Integer, Tree> entry : list2map.entrySet()) {
            if (entry.getValue().getPid() == null) {
                root.add(entry.getValue());
            } else {
                // 如果父树为空，不加人数据中
                Tree pTree = list2map.get(entry.getValue().getPid());
                if (!StringUtils.isEmpty(pTree)) {
                    list2map.get(entry.getValue().getPid()).getChildren().add(entry.getValue());
                }
            }
        }
        return root;
    }
}
